﻿/*-------------------------------------------------------------------------
* 命名空间: SiliconSelect.Common/LogHelper
* 类       名: LogHelper
* 功      能:  LogHelper的类,使用log4net来构建的LogHelper类
* 时      间:  2023/6/20 15:04:16
* 版      本:  V1.0
* 作      者:  Fioman
* 格      言:  Talk is cheap,show me the code ^_^
*-------------------------------------------------------------------------*/
using log4net;
using log4net.Appender;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using XrayDirection.Extensions;

namespace SiliconSelect.Common
{
    public abstract class LogHelper
    {
        // 同一条日志,换行显示的时候左边的填充区域,就是日志显示的时候,内容对齐,日期时间在左边.
        private static readonly ILog Logger;

        public static CancellationTokenSource clearLogToken = new CancellationTokenSource();

        // 静态构造函数
        static LogHelper()
        {
            Logger = LogManager.GetLogger(@"MainProgram");
            Task.Run(async () =>
            {
                try
                {
                    while (!clearLogToken.Token.IsCancellationRequested)
                    {
                        DoClearOverDue();
                        WriteLog("清除过期日志");
                        await Task.Delay(43200000, clearLogToken.Token);
                    }
                }
                catch (OperationCanceledException)
                {
                    WriteLog("清理日志任务已取消");
                }
                catch (Exception ex)
                {
                    WriteLog("清理日志任务发生异常: " + ex.GetFullException(), LogType.Exception);
                }
            });
        }

        /// <summary>
        /// 具体的清理过期日志的任务
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private static void DoClearOverDue()
        {
            int temp = Convert.ToInt32(ConfigurationManager.AppSettings["OverdueDays"]);
            int days = temp == 0 ? 15 : temp;
            DateTime now = DateTime.Now.AddDays(-days);
            IAppender[] array = Logger.Logger.Repository.GetAppenders();
            foreach (var item in array)
            {
                if (!(item is RollingFileAppender roll))
                {
                    continue;
                }
                string? dir = Path.GetDirectoryName(roll.File);
                string[] files = Directory.GetFiles(dir!, "*.log*");
                foreach (string filePath in files)
                {
                    FileInfo file = new FileInfo(filePath);
                    if (file.CreationTime < now || file.LastWriteTime < now)
                    {
                        try
                        {
                            file.Delete();
                        }
                        catch (Exception ex)
                        {
                            WriteLog("日志清理失败: " + ex.GetFullException(), LogType.Exception);
                        }
                    }
                }
            }
        }


        private static List<string> GetAlarmInfoByErrorCodeMain(string errorCode)
        {
            List<string> alarmInfo = new List<string>();
            try
            {
                return alarmInfo;
            }
            catch (Exception)
            {
                alarmInfo.Add($"获取报警代码{errorCode} 出现异常");
                alarmInfo.Add($"获取报警代码{errorCode} 出现异常");
                return alarmInfo;
            }
        }

        /// <summary>
        /// 日志写入,有的日志不一定要从数据库去获取.
        /// </summary>
        /// <param name="type">日志的种类</param>
        /// <param name="message">具体的日志信息</param>
        public static void WriteLog(string? message, LogType logType = LogType.Info, string errorCode = "P00", bool isInsert = false)
        {
            if (errorCode != "P00")
            {
            }
            switch (logType)
            {
                case LogType.Info:
                    Logger.Info(message);
                    break;
                case LogType.Debug:
                    Logger.Debug(message);
                    break;
                case LogType.Warn:
                    Logger.Warn(message);
                    break;
                case LogType.Exception:
                    Logger.Error(message);
                    break;
                case LogType.Fatal:
                    Logger.Fatal(message);
                    break;
                case LogType.TestShow:
                    Logger.Debug(message);
                    break;
            }
        }

    }


    public enum LogType
    {
        Info,
        Debug,
        Warn,
        Exception,
        Fatal,
        TestShow, // 用来测试流程的时候显示,方便查看
    }
}
